package com.usdt.system.cp.utils;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import lombok.extern.log4j.Log4j2;

@Log4j2
public class FileDownloader {

	/**
	 * 从指定 URL 下载文件并保存到本地路径
	 *
	 * @param fileUrl  文件的 URL 地址（如："https://example.com/file.txt"）
	 * @param savePath 本地保存路径（如："C:/downloads/file.txt"）
	 * @throws IOException 如果下载或写入过程中发生错误
	 */
	public static void downloadFile(String fileUrl, String savePath) throws IOException {
		URL url = new URL(fileUrl);
		HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
		int responseCode = httpConn.getResponseCode();

		// 检查响应码是否为 HTTP OK
		if (responseCode != HttpURLConnection.HTTP_OK) {
			throw new IOException("Server returned non-OK status code: " + responseCode);
		}

		try (BufferedInputStream in = new BufferedInputStream(httpConn.getInputStream());
				FileOutputStream out = new FileOutputStream(savePath)) {

			byte[] buffer = new byte[1024];
			int bytesRead;
			while ((bytesRead = in.read(buffer, 0, buffer.length)) != -1) {
				out.write(buffer, 0, bytesRead);
			}

			log.info("Download completed. File saved to: " + savePath);
		} catch (IOException e) {
			log.error("Error occurred during download or file write: " + e.getMessage());
			e.printStackTrace();
		}
	}
}
